<template>
	<el-dialog
		:title="dataForm.id ? '编辑数据集' : '创建数据集'"
		:close-on-click-modal="false"
		v-model="visible"
		lock-scroll
		width="800px"
		@close="handleClose"
	>
		<el-form :model="dataForm" label-width="110px" :rules="formRules" ref="dataFormRef">
			<el-form-item label="数据集名称" prop="datasetName">
				<el-popover width="30%" :visible="openTree" placement="bottom" trigger="click">
					<template #reference>
						<el-input :value="dataForm.datasetName" :disabled="dataForm.id ? true : false" @click.stop="openTree = true" placeholder="选择数据集"></el-input>
					</template>
					<div v-click-outside="() => (openTree = false)" style="height: 300px;overflow: auto" class="popover">
						<el-tree
							ref="treeRef"
							:data="datasetOptions"
							:props="props"
							:lazy="true"
							:load="loadNode"
							:node-key="'id'"
							highlight-current
							:expand-on-click-node="false"
							:current-node-key="dataForm.datasetId"
							accordion
							:filter-node-method="filterNode"
							@node-click="selectDataset"
						>
							<template #default="{ node, data }">
								<div class="metadata-tree-node">
									<!-- 如果是目录-->
									<img v-if="data.icon == '/src/assets/folder.png'" src="/src/assets/folder.png" />
									<img v-if="data.icon == '/src/assets/database.png'" src="/src/assets/database.png" />
									<el-text style="width: 10em; margin-left: 8px">{{ data.name }}</el-text>
								</div>
							</template>
						</el-tree>
					</div>
				</el-popover>
				<!-- <el-select
					v-model="dataForm.datametaId"
					class="input"
					clearable
					style="width: 100%"
					placeholder="请选择数据集"
					@change="selectDataset"
				>
					<el-option v-for="option in datasetOptions" :key="option.value" :label="option.label" :value="option.value"> </el-option>
				</el-select> -->
			</el-form-item>
			<el-form-item label="数据集名" prop="datasetCode">
				<el-input disabled v-model="dataForm.datasetCode" placeholder="请输入数据集名" />
			</el-form-item>
			<el-form-item label="版本时间" prop="versionId">
				<el-input v-model="dataForm.versionId" placeholder="请输入版本时间" disabled />
			</el-form-item>
			<el-form-item label="核验状态" prop="invalidFlag">
				<el-switch v-model="dataForm.invalidFlag" :active-value="'0'" :inactive-value="'1'"></el-switch>
			</el-form-item>
			<el-form-item label="备注" prop="datasetDescription">
				<el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="dataForm.datasetDescription"> </el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button type="primary" @click="handleSave()">保 存</el-button>
			<el-button @click="visible = false">取 消</el-button>
		</template>
	</el-dialog>
</template>
<script setup lang="ts">
import { nextTick, reactive, ref, onMounted } from 'vue'
import { ElMessage, ClickOutside as vClickOutside } from 'element-plus'
import timeFormater from 'time-formater'
import { listChildApi, delTreeNodeApi, listKeywordApi } from '@/api/data-governance/metadata'
import { saveRuleDataset, metaDataList } from '@/api/verification-dataset/index'
import type Node from 'element-plus/es/components/tree/src/model/node'

const emit = defineEmits(['close'])

interface Tree {
	name: string
	leaf?: boolean
}
const props = {
	label: 'name',
	children: 'children',
	isLeaf: 'leaf'
}
const treeRef = ref()
const openTree = ref(false)
const visible = ref(false)
const checkStatus = ref<boolean>(true)
const dataFormRef = ref<any>()
const datasetOptions = ref([])
let dataForm = reactive({
	datametaId: '',
	datasetName: '',
	datasetCode: '',
	versionId: '',
	invalidFlag: '',
	datasetDescription: ''
})

const formRules = ref({
	datametaName: [{ required: true, message: '请输入数据集名称', trigger: 'blur' }],
	datasetCode: [{ required: true, message: '请输入数据集名', trigger: 'blur' }]
})

const init = (data: any) => {
	visible.value = true

	nextTick(() => {
		if (data) {
			Object.assign(dataForm, data)
		} else {
			dataForm.id = ''
			dataForm.versionId = timeFormater().format('YYYYMMDD')
		}
	})
}

// 数据集列表
const getDataSetList = () => {
	listKeywordApi('').then(res => {
		if (res.code == 0) {
			datasetOptions.value = res.data
		}
	})
}
const loadNode = async (node: Node, resolve: (data: Tree[]) => void) => {
	if (node.level == 0) {
		return resolve(datasetOptions.value)
	}
	if (node.level >= 1) {
		if (node.data.children) {
			resolve(node.data.children)
		} else {
			const { data } = await listChildApi(node.data.id)
			// 如果是数据库不显示展开按钮
			data.forEach((item: any) => {
				if (item.icon == '/src/assets/database.png') {
					item.leaf = true
				}
			})
			resolve(data)
		}
	}
	treeRef.value!.filter()
}
const selectDataset = (val: any) => {
	console.log('选中', val)
	if (val.icon == '/src/assets/folder.png') {
		ElMessage('请选择数据库类型')
	} else {
		dataForm.datasetName = val.name
		dataForm.datasetCode = val.code
		dataForm.datametaId = val.id
		openTree.value = false
	}
	// dataForm.datasetName = datasetOptions.value.filter(item => { return item.id == val.id })[0].name
	// dataForm.datasetCode = datasetOptions.value.filter(item => { return item.id == val.id })[0].id
}
// 过滤不是目录或数据库的节点
const filterNode = (value: string, data: Tree) => {
	return data.icon == '/src/assets/folder.png' || data.icon == '/src/assets/database.png'
}

onMounted(() => {
	getDataSetList()
})

const handleSave = () => {
	// dataForm.invalidFlag = checkStatus.value ? '0' : '1'
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		} else {
			saveRuleDataset(dataForm).then(
				res => {
					ElMessage({
						type: 'success',
						duration: 1000,
						message: res.msg,
						onClose: () => {
							visible.value = false
							emit('close')
						}
					})
				},
				// error => {
				// 	ElMessage({
				// 		type: 'error',
				// 		duration: 1000,
				// 		message: error.msg
				// 	})
				// }
			)
		}
	})
}

const handleClose = () => {
	dataFormRef.value.resetFields()
	visible.value = false
}

defineExpose({
	init
})

// export default {
//   data() {
//     return {
//       visible: false,
//       checkStatus: true,
//       dataForm: {
//         datasetName: "",
//         datasetCode: "",
//         versionId: "",
//         invalidFlag: "",
//         datasetDescription: "",
//         datasetDescription: "",
//       },
//       formRules: {
//         datasetName: [
//           { required: true, message: "请输入数据集名称", trigger: "blur" },
//         ],
//         datasetCode: [
//           { required: true, message: "请输入数据集名", trigger: "blur" },
//         ],
//       },
//     };
//   },

//     init(data) {
//       let that = this;
//       if (data) {
//         that.dataForm = {
//           ...data
//         };
//         if (that.dataForm.invalidFlag === "0") {
//           that.checkStatus = true;
//         } else {
//           that.checkStatus = false;
//         }
//       } else {
//         that.dataForm = {
//           datasetName: "",
//           datasetCode: "",
//           versionId: that.timeFormater().format("YYYYMMDD"),
//           invalidFlag: "",
//           datasetDescription: "",
//         };
//         that.checkStatus = true;
//       }
//       that.visible = true;
//     }
//     goBack() {
//       this.visible = false;
//     }
//     handleSave() {
//       this.dataForm.invalidFlag = this.checkStatus ? "0" : "1";
//       this.$refs.dataForm.validate((valid) => {
//         if (valid) {
//           // console.log(this.dataForm);
//           if (this.dataForm.ID) {
//             updateRuleDataset(this.dataForm).then(
//               (res) => {
//                 this.$message({
//                   type: "success",
//                   duration: 1000,
//                   message: res.data.message,
//                   onClose: () => {
//                     this.$emit("close");
//                   },
//                 });
//               },
//               (error) => {
//                 this.$message({
//                   type: "error",
//                   duration: 1000,
//                   message: error.message,
//                 });
//               }
//             );
//           } else {
//             saveRuleDataset(this.dataForm).then(
//               (res) => {
//                 this.$message({
//                   type: "success",
//                   duration: 1000,
//                   message: res.data.message,
//                   onClose: () => {
//                     this.$emit("close");
//                   },
//                 });
//               },
//               (error) => {
//                 this.$message({
//                   type: "error",
//                   duration: 1000,
//                   message: error.message,
//                 });
//               }
//             );
//           }
//         } else {
//           return false;
//         }
//       });
//     }

// };
</script>
<style lang="scss" scoped>
</style>